/**
 * 章节信息
 * */

let $table = $('#chapter-table'),
    $remove = $('#remove'),
    selections = [],
    key = 'Id';

let pageNumber = 1, pageSize = 10;
let pageListUrl = "/Chapter/PageList";
let circleModalId = "circleModal", $circleModal = null; // 圆形进度条窗体及对象

$(function () {

    $table = $('#chapter-table'),
        $remove = $('#remove');

    $("#btnAdd").unbind('click').bind('click', function () {
        $("#editModelLabel").html("章节信息添加");
        $('#editModel').modal('toggle');
    });

    initTable();

    // 关键词查询
    $('input[name="search"]').bind('keydown', function (event) {
        if (event.keyCode == "13") {
            pageNumber = 1;
            refreshTable();
        }
    });

    // 搜索
    $('#btnSearch').unbind('click').bind('click', function () {
        pageNumber = 1;
        refreshTable();
    });

    // 清空查询条件
    $('#btnClear').unbind('click').bind('click', function () {
        $('#toolbar form')[0].reset();
        pageNumber = 1;
        refreshTable();
    });


    // 抓取小说内容
    $("#btnCrawlContent").unbind('click').bind('click', function () {

        var novelName = $("#NovelName").val();
        Hsp.Modal.CircleMessage(circleModalId, `小说『${novelName}』正在抓取中`);
        $("#" + circleModalId).modal("toggle");

        //setTimeout(function () {
        //    $("#" + circleModalId).modal("hide");
        //}, 5000); webId

        var url = "/Chapter/Crawl/" + $("#NovelId").val();

        //$.get("demo_test.asp", function (data, status) { 
        //    alert("Data: " + data + "\nStatus: " + status);
        //});

        $.get(url + "?rnd=" + (Math.random() * 10), function (data) {
            //console.log(data);
            if (data && data.success) {
                toastr.success(data.message, "成功");
                refreshTable();
                $("#" + circleModalId).modal("hide");
            } else {
                toastr.error(data.message, "失败");
            }
        });

    });

    // 清空小说内容
    $("#btnClearContent").unbind('click').bind('click', function () {

        if (confirm("您确定要清空小说内容吗？")) {

            let ids = getIdSelections();

            if (ids.length == 0) {
                toastr.info("请选择要清空的章节", "提示");
                return;
            }

            $.get("/Content/Clear/" + ids + "?rnd=" + (Math.random() * 10), function (data) {
                if (data && data.success) {
                    toastr.success(data.message, "成功");
                    refreshTable();
                } else {
                    toastr.error(data.message, "失败");
                }
            });
        }
    });

    // 清空小说数据
    $("#btnClearNovelData").unbind('click').bind('click', function () {
        if (confirm("您确定要清空小说数据吗？")) {
            $.get("/Chapter/Clear/" + $("#NovelId").val() + "?rnd=" + (Math.random() * 10), function (data) {
                if (data && data.success) {
                    toastr.success(data.message, "成功");
                    refreshTable();
                } else {
                    toastr.error(data.message, "失败");
                }
            });
        }
    });

    // 下载小说文件
    $("#btnDownload").unbind('click').bind('click', function () {
        // 小说下载
        Page("/Novel/Download/" + $("#NovelId").val() + "?rnd=" + (Math.random() * 10));
    });
});

// 刷新表格数据
function refreshTable() {
    $table.bootstrapTable({ url: pageListUrl });
    $table.bootstrapTable('refresh', { pageNumber: pageNumber, pageSize: pageSize });
}

// 初始化表
function initTable() {

    //先销毁表格
    $table.bootstrapTable('destroy');

    $table.bootstrapTable({
        height: getHeight(),
        method: 'get', // 请求方式（*）
        dataType: "json", // 数据类型
        url: pageListUrl, // 请求后台地址,
        toolbar: '#toolbar', //工具按钮用哪个容器
        striped: true, // 使表格带有条纹
        uniqueId: key, // 唯一标识
        idField: key, // 标识哪个字段为id主键
        pagination: true, // 在表格底部显示分页工具栏
        pageSize: pageSize, // 分页大小
        pageNumber: pageNumber, // 当前页码
        pageList: [10, 20, 50, 100, 200, 500],
        sidePagination: "server", //表格分页的位置
        //设置为undefined可以获取pageNumber，pageSize，searchText，sortName，sortOrder
        //设置为limit可以获取limit, offset, search, sort, order
        queryParamsType: "undefined",
        queryParams: function queryParams(params) { //设置查询参数
            var param = {
                pageNumber: params.pageNumber,
                pageSize: params.pageSize,
                title: $("input[name='search']").val()
                , startDate: $("input[name='startDate']").val()
                , endDate: $("input[name='endDate']").val()
                , novelId: $("#NovelId").val()
            };
            pageNumber = params.pageNumber;
            return param;
        },
        columns: [
            [
                {
                    field: 'checked',
                    checkbox: true
                }, {
                    title: '序号',
                    field: 'RowNumber',
                    width: 60,
                    align: 'center',
                    formatter: function (value, row, index) {
                        var options = $table.bootstrapTable('getOptions');
                        return options.pageSize * (options.pageNumber - 1) + index + 1;
                    }
                }, {
                    title: '操作',
                    width: 90,
                    halign: 'center',
                    align: 'center',
                    events: operateEvents,
                    formatter: operateFormatter
                }, {
                    field: 'ChapterUrl',
                    title: '章节地址',
                    width: 120,
                    halign: 'center',
                    align: 'left',
                    formatter: tipsFormatter
                }, {
                    field: 'NextUrl',
                    title: '下一页地址',
                    width: 120,
                    halign: 'center',
                    align: 'left',
                    formatter: tipsFormatter
                }, {
                    field: 'SourceTitle',
                    title: '源标题',
                    width: 120,
                    halign: 'center',
                    align: 'left',
                    formatter: tipsFormatter
                }, {
                    field: 'ChapterTitle',
                    title: '章节标题',
                    width: 120,
                    halign: 'center',
                    align: 'left',
                    formatter: tipsFormatter
                }, {
                    field: 'ChapterIdx',
                    title: '章节索引',
                    width: 120,
                    halign: 'center',
                    align: 'center',
                    formatter: tipsFormatter
                }, {
                    field: 'ChapterName',
                    title: '章节序号',
                    width: 120,
                    halign: 'center',
                    align: 'center',
                    formatter: tipsFormatter
                }, {
                    field: 'HeadWord',
                    title: '标题文本',
                    width: 120,
                    halign: 'center',
                    align: 'left',
                    formatter: tipsFormatter
                }, {
                    field: 'WordCount',
                    title: '章节字数',
                    width: 120,
                    halign: 'center',
                    align: 'right',
                    formatter: tipsFormatter
                }, {
                    field: 'ValidChapterName',
                    title: '有效章节',
                    width: 120,
                    halign: 'center',
                    align: 'center',
                    formatter: tipsFormatter
                }, {
                    field: 'CreateTime',
                    title: '添加时间',
                    width: 105,
                    halign: 'center',
                    align: 'center',
                    formatter: function (value, row, index) {
                        return (value == null || value.length == 0) ? "" : value.toDateTimeString("yyyy-MM-dd hh:mm");
                    }
                }, {
                    field: 'UpdateTime',
                    title: '更新时间',
                    width: 105,
                    halign: 'center',
                    align: 'center',
                    formatter: function (value, row, index) {
                        return (value == null || value.length == 0) ? "" : value.toDateTimeString("yyyy-MM-dd hh:mm");
                    }
                }
            ]
        ],
        formatLoadingMessage: function () {
            return "请稍等，正在加载中...";
        },
        formatNoMatches: function () { //没有匹配的结果
            return '无符合条件的记录';
        }
    });

    $table.find("thead").addClass("table-dark");

    setTimeout(function () {
        $table.bootstrapTable('resetView');
        $('[data-toggle="tooltip"]').tooltip();
    }, 200);

    $table.on('check.bs.table uncheck.bs.table ' +
        'check-all.bs.table uncheck-all.bs.table', function () {
            $remove.prop('disabled', !$table.bootstrapTable('getSelections').length);

            // save your data, here just save the current page

            selections = getIdSelections();

            // push or splice the selections if you want to save all data selections

        });

    $remove.click(function () { // 批量删除
        var ids = getIdSelections();
        $remove.prop('disabled', true);
        BatchDelete(ids.toString()); // 批量删除
    });

    $(window).resize(function () {
        $table.bootstrapTable('resetView', {
            height: getHeight()
        });
    });
}

// 获取选择项
function getIdSelections() {
    return $.map($table.bootstrapTable('getSelections'), function (row) {
        return row[key];
    });
}

// 操作内容格式化
function operateFormatter(value, row, index) {
    let edit = ['<a class="edit" href="javascript:void(0)" title="修改章节信息">',
        '<i class="glyphicon glyphicon-edit"></i>',
        '</a>'];

    let remove = ['  <a class="remove" href="javascript:void(0)" title="删除章节信息">',
        '<i class="glyphicon glyphicon-remove"></i>',
        '</a>'];
    edit = edit.concat(remove);
    return edit.join('');
}

// 操作事件响应
window.operateEvents = {
    'click .edit': function (e, value, row, index) {
        //alert('You click edit action, row: ' + JSON.stringify(row));

        //debugger;
        //console.info("编辑前获取行数据：");
        console.info(row);

        $("#Id").val(row.Id); // 章节编号
        $("#NovelId").val(row.NovelId); // 小说编号
        $("#ChapterUrl").val(row.ChapterUrl); // 小说地址
        $("#NextUrl").val(row.NextUrl); // 下一章地址
        $("#SourceTitle").val(row.SourceTitle); // 源标题
        $("#ChapterTitle").val(row.ChapterTitle); // 章节标题
        $("#ChapterIdx").val(row.ChapterIdx); // 章节索引
        $("#ChapterName").val(row.ChapterName); // 章节序号
        $("#HeadWord").val(row.HeadWord); // 标题文本
        $("#WordCount").val(row.WordCount); // 章节字数
        $("#ValidChapter").val(row.ValidChapter); // 有效章节：0-否；1-是；
        $("#CreateTime").val(row.CreateTime); // 添加时间
        $("#UpdateTime").val(row.UpdateTime); // 更新时间

        $("#editModelLabel").html("章节信息修改");
        $('#editModel').modal('toggle');
    },
    'click .remove': function (e, value, row, index) {
        Delete(row[key]); // 删除行数据
    }
};

/// <summary>
/// 物理删除数据
/// </summary>

function Delete(id) {
    if (confirm("您确定要删除该章节信息吗？")) {
        $.ajax({
            type: "POST",
            url: "/Chapter/Delete/" + id + "?rnd=" + (Math.random() * 10),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (rst) {
                //console.info(rst);
                if (rst && rst.success) {
                    refreshTable();
                    toastr.success(data.message, "成功");
                } else {
                    toastr.error(data.message, "失败");
                }
            }
        });
    }
}

/// <summary>
/// 批量物理删除
/// </summary>

function BatchDelete(ids) {
    if (confirm("您确定要批量删除这些章节信息吗？")) {
        $.ajax({
            type: "POST",
            url: "/Chapter/BatchDelete/" + ids + "?rnd=" + (Math.random() * 10),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (rst) {
                //console.info(rst);
                if (rst && rst.success) {
                    refreshTable();
                    toastr.success(data.message, "成功");
                } else {
                    toastr.error(data.message, "失败");
                }
            }
        });
    }
}

$(function () {

    $('#editModel').on('hidden.bs.modal', function () { // 关闭模态窗体事件
        $("#editModel form")[0].reset();
        $("#btnSave").prop("disabled", false); // 解除保存按钮禁用
        $("#editModel form input[type='hidden']").val("");
    });

    $("#btnSave").unbind("click").bind("click", function () { // 章节信息数据保存

        let txtId = $("#Id").val(); // 章节编号
        let txtNovelId = $("#NovelId").val(); // 小说编号
        let txtChapterUrl = $("#ChapterUrl").val(); // 小说地址
        let txtNextUrl = $("#NextUrl").val(); // 下一章地址
        let txtSourceTitle = $("#SourceTitle").val(); // 源标题
        let txtChapterTitle = $("#ChapterTitle").val(); // 章节标题
        let txtChapterIdx = $("#ChapterIdx").val(); // 章节索引
        let txtChapterName = $("#ChapterName").val(); // 章节序号
        let txtHeadWord = $("#HeadWord").val(); // 标题文本
        let txtWordCount = $("#WordCount").val(); // 章节字数
        let txtValidChapter = $("#ValidChapter").val(); // 有效章节：0-否；1-是；
        let txtCreateTime = $("#CreateTime").val(); // 添加时间
        let txtUpdateTime = $("#UpdateTime").val(); // 更新时间

        if (txtChapterIdx == undefined || txtChapterIdx.length == 0) {
            txtChapterIdx = "0";
        }
        if (txtWordCount == undefined || txtWordCount.length == 0) {
            txtWordCount = "0";
        }
        if (txtValidChapter == undefined || txtValidChapter.length == 0) {
            txtValidChapter = "0";
        }

        // 字符串输入超长处理

        if (txtChapterName && txtChapterName.length > 20) {
            toastr.error('章节序号超过设定长度20！');
            $("#ChapterName").focus();
            return;
        }

        $("#btnSave").prop("disabled", "disabled");

        // 字符串中异常字符处理
        if (txtChapterUrl != undefined && txtChapterUrl.length > 0) {
            txtChapterUrl = txtChapterUrl.replace(/'|\\|\"|\||>|<|\*|\?/g, ""); // 小说地址
        }
        if (txtNextUrl != undefined && txtNextUrl.length > 0) {
            txtNextUrl = txtNextUrl.replace(/'|\\|\"|\||>|<|\*|\?/g, ""); // 下一章地址
        }
        if (txtSourceTitle != undefined && txtSourceTitle.length > 0) {
            txtSourceTitle = txtSourceTitle.replace(/'|\\|\"|\||>|<|\*|\?/g, ""); // 源标题
        }
        if (txtChapterTitle != undefined && txtChapterTitle.length > 0) {
            txtChapterTitle = txtChapterTitle.replace(/'|\\|\"|\||>|<|\*|\?/g, ""); // 章节标题
        }
        if (txtChapterName != undefined && txtChapterName.length > 0) {
            txtChapterName = txtChapterName.replace(/'|\\|\"|\||>|<|\*|\?/g, ""); // 章节序号
        }
        if (txtHeadWord != undefined && txtHeadWord.length > 0) {
            txtHeadWord = txtHeadWord.replace(/'|\\|\"|\||>|<|\*|\?/g, ""); // 标题文本
        }

        let obj = {};
        obj.Id = txtId; // 章节编号
        obj.NovelId = txtNovelId; // 小说编号
        obj.ChapterUrl = txtChapterUrl; // 小说地址
        obj.NextUrl = txtNextUrl; // 下一章地址
        obj.SourceTitle = txtSourceTitle; // 源标题
        obj.ChapterTitle = txtChapterTitle; // 章节标题
        obj.ChapterIdx = txtChapterIdx; // 章节索引
        obj.ChapterName = txtChapterName; // 章节序号
        obj.HeadWord = txtHeadWord; // 标题文本
        obj.WordCount = txtWordCount; // 章节字数
        obj.ValidChapter = txtValidChapter; // 有效章节：0-否；1-是；
        obj.CreateTime = txtCreateTime; // 添加时间
        obj.UpdateTime = txtUpdateTime; // 更新时间

        //console.info(JSON.stringify(obj));

        $.ajax({
            type: "POST",
            url: "/Chapter/Save/?rnd=" + (Math.random() * 10),
            data: JSON.stringify(obj),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (rst) {
                //console.info(rst);
                if (rst && rst.success) {

                    refreshTable();

                    $("#editModel").modal("hide");
                    $("#btnSave").prop("disabled", "");
                } else {
                    toastr.error(rst.message, "失败");
                }
            }
        });
    });

});
